package frame.tool.web;

import frame.base.Ajax;
import frame.base.BaseWeb;
import frame.base.BootstrapTable;
import frame.tool.qo.StoryQo;
import frame.tool.service.StoryService;
import frame.tool.to.Story;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping(StoryWeb.DIR)
public class StoryWeb extends BaseWeb {

    public static final String DIR = "/tool/crawler/story";

    @Autowired
    private StoryService storyService;


    @RequestMapping("/index")
    public String index(Model model, StoryQo qo) {
        model.addAttribute("dir", DIR);
        model.addAttribute("qo", qo);
        return "tool/crawler/storylist";
    }
    @RequestMapping("/table")
    @ResponseBody
    public BootstrapTable<Story> table(StoryQo qo) {
        return storyService.pageList(qo);
    }

    @RequestMapping("/add")
    @ResponseBody
    public Ajax add(@Valid() Story story, BindingResult bd) {
        try {
            super.checkFormData(bd);
            storyService.addSelective(story);
            return Ajax.success(story.getId(),"数据创建成功！");
        } catch (Exception e) {
            return Ajax.faild("数据创建失败：" + e.getMessage());
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Ajax delete(String[] ids) {
        try {
            List<Integer> idList = strId2Integer(ids);
            int re =  storyService.delete(idList);
            return Ajax.success(re, "数据删除成功");
        } catch (Exception e) {
            return Ajax.faild("数据创建失败：" + e.getMessage());
        }
    }

    @RequestMapping("/update")
    @ResponseBody
    public Ajax update(@Valid() Story story, BindingResult bd) {
        try {
            checkFormData(bd);
            int re = storyService.updateSelective(story);
            return Ajax.success(re,"数据更新成功！");
        } catch (Exception e) {
            return Ajax.faild("数据更新失败：" + e.getMessage());
        }
    }
    /**
     * 保存爬虫获取的小说
     * 标题不存在就新增，存在就修改内容
     * @param story
     * @param bd
     * @return
     */
    @RequestMapping("/send")
    @ResponseBody
    public Ajax send(@Valid() Story story, BindingResult bd) {
        System.out.println(story.getTitle());
        System.out.println(story.getContent());
        try {
            super.checkFormData(bd);
            storyService.send(story);
            return Ajax.success(story.getId(),"小说保存成功！");
        } catch (Exception e) {
            return Ajax.faild("小说保存失败：" + e.getMessage());
        }
    }

    @RequestMapping("/reader.js")
    public String reader() {
        return "tool/crawler/reader";
    }
}
